//
//  Record.m
//  MUBATE
//
//  Created by sunbin on 2017/2/23.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "Record.h"
#import "RecordCell.h"
#import "RecentRecordModel.h"
#import "RequestManage.h"
#import "RecordDetails.h"
static NSString * RecordCellIdentifier = @"RecordCellIdentifier";


@interface Record ()<UITableViewDataSource ,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *recoderListArr;

@end

@implementation Record
{
    NSInteger pageIndex;
    
    NSArray *apiAry;
    NSArray *paramsAry;
    NSArray *modelAry;

    
    BOOL isRefreshLoad;
}

- (NSMutableArray *)recoderListArr
{
    if (!_recoderListArr) {
        _recoderListArr = [NSMutableArray array];
    }
    return _recoderListArr;
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    WEAKSELF;
    weakSelf.jHUDRect = SCREEN_RECT;//设置大小位置 确定jhud位置


    [weakSelf initView];//设置tableFooterView 注册xib
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataClear) name:CLEANRECORD object:nil];

    // 程序进入 默认
    [weakSelf getNetWork:0 pageCount:REFRESHCOUNT refresh:NO];//网络加载
    [weakSelf loadData];//设置刷新
    
    
    
    [weakSelf.hudView setJHUDReloadButtonClickedBlock:^() {
        [weakSelf activityLoad];
        
    }];
    


}

- (void)dataClear{
    [self.recoderListArr removeAllObjects];
    [self.tableView reloadData];
    

    [self performSelector:@selector(clearData) withObject:nil afterDelay:2.0];
}





-(void)clearData {
    [self.recoderListArr removeAllObjects];
    [self.tableView reloadData];

}














- (void)activityLoad{
    NSLog(@"_currentIndex==%ld" ,(long)_currentIndex);
    WEAKSELF;
    [weakSelf loadingCircleJoinAnimation:@"loadingCircleJoinAnimation" showAtView:weakSelf.view];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf getNetWork:weakSelf.currentIndex pageCount:REFRESHCOUNT refresh:NO];//网络加载

    });
    

}



- (void)setCurrentIndex:(NSInteger)currentIndex{
    _currentIndex = currentIndex;
    if (pageIndex == 0) {
        pageIndex = REFRESHCOUNT;
    }

    [self getNetWork:currentIndex pageCount:pageIndex refresh:YES];//这里设置Yes 当无限制刷新 获取最新接口接口api返回无数据bug
    
}
- (void)initView{
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self registerNib];
    

}

// 设置刷新
- (void)loadData{
    pageIndex = REFRESHCOUNT;
    WEAKSELF;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        pageIndex+=REFRESHCOUNT;
        [weakSelf getNetWork:weakSelf.currentIndex pageCount:pageIndex refresh:YES];
        [weakSelf.tableView.mj_header endRefreshing];            // 结束刷新
        isRefreshLoad = YES;

    }];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            pageIndex+=REFRESHCOUNT;
            [weakSelf getNetWork:weakSelf.currentIndex pageCount:pageIndex refresh:YES];
            // 结束刷新
            [weakSelf.tableView.mj_footer endRefreshing];
            isRefreshLoad = YES;

        });
    }];
}


-(void)getNetWork:(NSInteger)index pageCount:(NSInteger)page refresh:(BOOL)refresh{
    WEAKSELF;
    NSDictionary *params = @{
                             @"uid"  :@([YConfig getOwnID]),
                             @"start":@(0),
                             @"count":@(page),
                             @"type" :@(index),
                             @"sign" :SIGN
                             };
    
    apiAry    = @[STOREMONEYLOG];
    paramsAry = @[params];
    modelAry  = @[@"RecentRecordModel"];
    // 注意 缓存数据 有网数据获取优先级别  （当有网络时获取网络数据 当没有网络时网络获取失败的情况时获取缓存数据）


    [RequestManage requestApi:apiAry params:paramsAry model:modelAry responseCache:^(BOOL isHaveCash, NSInteger index, NSDictionary *cashDic, NSMutableArray *cashAry) {

        
    } refreshHeadler:^(int index) {
    } success:^(NSDictionary *succesSults, NSMutableArray *dataAry, NSString *successRequestmsg, NSInteger index) {
        [weakSelf getDataSource:dataAry refresh:refresh];//获取网络数据
    } failure:^(NSDictionary * failedSults ,NSMutableArray *arySults, responseState resMake, NSString* RequestError , NSInteger index) {
        //获取缓存数据 走缓存数据
        
        // bug 注意两点1离线刷新加载 2清理缓存 无数据 无网络 怎样做区分
        
        NSLog(@"%@  %@  ,%ld ,%@  ,%ld" ,failedSults ,arySults ,(long)resMake ,RequestError ,index);
        [weakSelf getDataSource:arySults refresh:refresh];
        
    } showHub:^(bool isShowHub, NSInteger index) {
        if (isShowHub) {
            if (refresh) {}else{
                [weakSelf loadingFailure:@"无数据" refreshTitle:@"Refresh ?" customImage:@"nullData" indicatorViewSize:CGSizeMake(130, 130) showAtView:weakSelf.view];
            }

        }
        
    }];
    
    
    
}

// 注意离线刷新时 造成数据清空操作
- (void)getDataSource:(NSMutableArray *)modelData refresh:(BOOL)refresh{
    WEAKSELF;
    [weakSelf jhudHide:weakSelf.view];
    
     weakSelf.recoderListArr = modelData;
    if (refresh && modelData.count ==0 ) {
        // 当清理数据时 bug 显示占位图  离线刷新不需要任何代码 但当数据清理时需要占位图显示
        if (isRefreshLoad) {

        }else{
            [weakSelf loadingFailure:@"无数据" refreshTitle:@"Refresh ?" customImage:@"nullData" indicatorViewSize:CGSizeMake(130, 130) showAtView:weakSelf.view];

        }

    }else{
        [weakSelf.tableView reloadData];

    }
}




- (void)registerNib{
    [self.tableView registerNib:[UINib nibWithNibName:@"RecordCell" bundle:nil] forCellReuseIdentifier:RecordCellIdentifier];

}

#pragma make -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    
    return self.recoderListArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RecordCell *cell = [tableView dequeueReusableCellWithIdentifier:RecordCellIdentifier forIndexPath:indexPath];
    RecentRecordModel *model = self.recoderListArr[indexPath.row];

    cell.model = model;
    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RecordDetails *recordDetails = [[RecordDetails alloc] initWithNibName:@"RecordDetails" bundle:nil];
    RecentRecordModel *model = (RecentRecordModel *)self.recoderListArr[indexPath.row];
    recordDetails.model = model;
    recordDetails.ty = [model.type integerValue] - 1;
    recordDetails.dataTy = modelTy;

    // 通知跳转
    [[NSNotificationCenter defaultCenter] postNotificationName:CHECKRECORDDETAILS object:nil userInfo:@{@"key":recordDetails}];
    

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kscaleHeight(60.f);
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {[cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 15)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {[cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 15)];
    }
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
